package com.miao.elm.service.impl;

import com.alibaba.fastjson.TypeReference;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.miao.elm.dao.OrdersDao;
import com.miao.elm.entity.BusinessEntity;
import com.miao.elm.entity.FoodEntity;
import com.miao.elm.entity.OrderdetailetEntity;
import com.miao.elm.entity.OrdersEntity;
import com.miao.elm.feign.BusinessFeignClient;
import com.miao.elm.feign.CartFeignClient;
import com.miao.elm.feign.FoodFeignClient;
import com.miao.elm.service.*;
import com.miao.elm.to.*;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.stream.Collectors;


@Service("ordersService")
public class OrdersServiceImpl extends ServiceImpl<OrdersDao, OrdersEntity> implements OrdersService {

    @Autowired
    CartFeignClient cartFeignClient;

    @Autowired
    OrderdetailetService orderdetailetService;

    @Autowired
    FoodFeignClient foodFeignClient;

    @Autowired
    BusinessFeignClient businessFeignClient;

    @Autowired
    ThreadPoolExecutor executor;

    @Override
    public String createOrders(OrderTo orderTo) throws ExecutionException, InterruptedException {
        String orderId = UUID.randomUUID().toString();
        OrdersEntity ordersEntity = new OrdersEntity();
        BeanUtils.copyProperties(orderTo, ordersEntity);
        ordersEntity.setOrderId(orderId);
        ordersEntity.setOrderDate(new Date());
        CartTo cartTo = new CartTo();
        cartTo.setUserId(orderTo.getUserId());
        cartTo.setBusinessId(orderTo.getBusinessId());
        CompletableFuture<Boolean> addToDetailTask = CompletableFuture.supplyAsync(() -> {
            //根据用户编号、商家编号从购物车表中查询所有数据，批量添加到订单明细表中
            List<FoodTo> cartInfo = cartFeignClient.listCart(cartTo);
            List<OrderdetailetEntity> collect = cartInfo.stream().map(v -> {
                OrderdetailetEntity orderdetailetEntity = new OrderdetailetEntity();
                orderdetailetEntity.setOrderId(orderId);
                orderdetailetEntity.setFoodId(v.getFoodId());
                orderdetailetEntity.setQuantity(v.getQuantity());
                return orderdetailetEntity;
            }).collect(Collectors.toList());
            orderdetailetService.saveBatch(collect);
            return true;
        }, executor);
        //根据用户编号、商家编号删除购物车表中的数据
        CompletableFuture<Void> removeFromCart = addToDetailTask.thenAcceptAsync((res) -> {
            cartFeignClient.removeCart(cartTo);
        }, executor);
        CompletableFuture.allOf(addToDetailTask, removeFromCart).get();
        this.baseMapper.insert(ordersEntity);
        return orderId;
    }

    @Override
    public OrderTo getOrdersById(String orderId) {
        OrderTo orderTo = new OrderTo();
        //查询订单信息
        OrdersEntity orderEntity = this.baseMapper.selectOne(new QueryWrapper<OrdersEntity>().eq("order_id", orderId));
        BeanUtils.copyProperties(orderEntity, orderTo);
        //查询当前商家名称
        BusinessEntity business = businessFeignClient.getBusinessById(orderEntity.getBusinessId());
        orderTo.setBusinessName(business.getBusinessName());
        //查询当前订单的所有订单项信息
        List<OrderdetailetEntity> detail = orderdetailetService.getDetail(orderId);
        List<OrderdetailetEntityTo> collect = detail.stream().map(v -> {
            OrderdetailetEntityTo orderdetailetEntityTo = new OrderdetailetEntityTo();
            BeanUtils.copyProperties(v, orderdetailetEntityTo);
            FoodEntity food = foodFeignClient.getFoodInfo(v.getFoodId()).getData(new TypeReference<FoodEntity>(){});
            orderdetailetEntityTo.setFoodEntity(food);
            return orderdetailetEntityTo;
        }).collect(Collectors.toList());
        orderTo.setBusiness(collect);
        System.out.println(orderTo);
        return orderTo;
    }

    @Override
    public List<OrdersTo> listOrdersByUserId(String userId) {
        List<OrdersEntity> orders = this.baseMapper.selectList(new QueryWrapper<OrdersEntity>().eq("user_id", userId));
        List<OrdersTo> list = new ArrayList<>();
        for (OrdersEntity order : orders) {
            OrdersTo ordersTo = new OrdersTo();
            ordersTo.setUserId(userId);
            ordersTo.setOrderId(order.getOrderId());
            ordersTo.setOrderState(order.getOrderState());
            ordersTo.setBusinessId(order.getBusinessId());
            ordersTo.setOrderTotal(order.getOrderTotal());
            ordersTo.setOrderDate(order.getOrderDate());
            //当前订单的商家信息
            BusinessTo businessTo = new BusinessTo();
            BusinessEntity business = businessFeignClient.getBusinessById(order.getBusinessId());
            businessTo.setBusinessName(business.getBusinessName());
            businessTo.setDeliveryPrice(business.getDeliveryPrice());
            ordersTo.setBusiness(businessTo);
            //当前订单的食品信息
            List<OrderdetailetEntity> detail = orderdetailetService.getDetail(order.getOrderId());
            List<FoodTo> collect = detail.stream().map(v -> {
                FoodTo foodTo = new FoodTo();
                FoodEntity food = foodFeignClient.getFoodInfo(v.getFoodId()).getData(new TypeReference<FoodEntity>(){});
                foodTo.setFoodName(food.getFoodName());
                foodTo.setFoodId(v.getFoodId());
                foodTo.setFoodPrice(food.getFoodPrice());
                foodTo.setQuantity(v.getQuantity());
                return foodTo;
            }).collect(Collectors.toList());
            ordersTo.setList(collect);
            list.add(ordersTo);
        }
        return list;
    }
}